"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HallServer_SocketMsgHandler = void 0;
const UserDao_1 = require("../account_server/dao/UserDao");
const UserResourceDao_1 = require("../account_server/dao/UserResourceDao");
const UserEntity_1 = require("../account_server/entity/UserEntity");
const AccountModel_1 = require("../account_server/model/AccountModel");
const UserModel_1 = require("../account_server/model/UserModel");
const ChannelConfig_1 = require("../src/config/ChannelConfig");
const ErrorCode_1 = require("../src/config/ErrorCode");
const GameConfig_1 = require("../src/config/GameConfig");
const RoomConfig_1 = require("../src/config/RoomConfig");
const RoomConfig_Mj_1 = require("../src/config/RoomConfig_Mj");
const ServerConfig_1 = require("../src/config/ServerConfig");
const SocketClientReqManager_1 = require("../src/engine/socketclient/SocketClientReqManager");
const SocketConnectionManager_1 = require("../src/engine/socketserver/socket/SocketConnectionManager");
const DateUtil_1 = require("../src/engine/utils/DateUtil");
const Logger_1 = require("../src/engine/utils/Logger");
const jhaoproto_1 = require("../src/lib/net/protobuf/jhaoproto");
const ProtoManager_1 = require("../src/lib/net/protobuf/ProtoManager");
const ResponseModel_1 = require("../src/model/ResponseModel");
const RoomManager_1 = require("../src/server/RoomManager");
const ServerManager_1 = require("../src/server/ServerManager");
const WebVersionModel_1 = require("../web_server/model/WebVersionModel");
const Club_SocketMsgHandler_1 = require("./Club_SocketMsgHandler");
const UserRoomDao_1 = require("./dao/UserRoomDao");
const RoomModel_1 = require("./model/RoomModel");
const RoomPlayer_1 = require("./model/RoomPlayer");
class HallServer_SocketMsgHandler {
    static onEventSocketGata(socketConnect, msg) {
        // Logger.log("HallServer_SocketMsgHandler=", msg)
        if (this.checkServer(socketConnect)) {
            try {
                if (msg.cmdIndex == jhaoproto_1.JhaoProto.CmdIndex.Login) {
                    this.onReqLogin(socketConnect, msg);
                }
                else {
                    if (socketConnect.isLogin()) {
                        if (msg.cmdIndex == jhaoproto_1.JhaoProto.CmdIndex.Ping) {
                            this.onReqPing(socketConnect, msg);
                        }
                        else if (msg.cmdIndex == jhaoproto_1.JhaoProto.CmdIndex.create_room) {
                            this.create_room(socketConnect, msg);
                        }
                        else {
                            Club_SocketMsgHandler_1.Club_SocketMsgHandler.onEventSocketGata(socketConnect, msg);
                        }
                    }
                    else {
                        socketConnect.sendErrorToClient(0, jhaoproto_1.JhaoProto.ErrorCodeWs.LoginError_NoLogin, "账号未登录");
                    }
                }
            }
            catch (error) {
                Logger_1.Logger.warn("allServer_SocketMsgHand error==", error, socketConnect.account, socketConnect.user, socketConnect.ip, socketConnect.id, msg);
            }
        }
    }
    static checkWeihu(socketConnect) {
        if (ServerConfig_1.ServerConfig.nowServerConfig.status == ServerConfig_1.ServerConfig.Status_Type.Weihu) {
            socketConnect.sendErrorToClient(0, jhaoproto_1.JhaoProto.ErrorCodeWs.Server_Weihu, ErrorCode_1.ErrorCode.code2Msg.get(ErrorCode_1.ErrorCode.Code.Server_Weihu));
            return true;
        }
    }
    static checkServer(socketConnect) {
        if (ServerConfig_1.ServerConfig.nowServerConfig.status == ServerConfig_1.ServerConfig.Status_Type.Normal) {
            return true;
        }
        else if (ServerConfig_1.ServerConfig.nowServerConfig.status == ServerConfig_1.ServerConfig.Status_Type.Weihu) {
            return true;
        }
    }
    static onReqLogin(new_conn, socketMsg) {
        return __awaiter(this, void 0, void 0, function* () {
            Logger_1.Logger.log("on_req_login====", socketMsg);
            let loginProto = ProtoManager_1.ProtoManager.instance.decode(jhaoproto_1.JhaoProto.ReqLogin, socketMsg.data);
            let respModel = yield AccountModel_1.AccountModel.login_async(loginProto.account, loginProto.token);
            if (respModel.code == ErrorCode_1.ErrorCode.Code.Suc) {
                let old_conn_list = SocketConnectionManager_1.SocketConnectionManager.instance.getSocketConnectionByUser(loginProto.account);
                for (let i = 0; i < old_conn_list.length; i++) {
                    let old_conn = old_conn_list[i];
                    if (old_conn && old_conn.id != new_conn.id) {
                        old_conn.sendErrorToClient(0, jhaoproto_1.JhaoProto.ErrorCodeWs.LoginError_MultiLogin, "异地登录");
                        old_conn.gotoClose();
                    }
                }
                new_conn.account = loginProto.account;
                let userData = yield UserDao_1.UserDao.get_user_data_by_account(loginProto.account);
                if (userData) {
                    if (userData.status != GameConfig_1.GameConfig.Status_Type.Normal) {
                        respModel.code = ErrorCode_1.ErrorCode.Code.Feng_jin;
                        respModel.msg = "用户被冻结，请联系客服";
                    }
                    else {
                        userData.ip = new_conn.ip;
                        userData.last_login_time = DateUtil_1.default.formatDateStr(DateUtil_1.default.now());
                        userData = yield UserDao_1.UserDao.update_user(userData);
                        if (!userData) {
                            respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                            respModel.msg = "用户登录更新数据失败";
                        }
                    }
                }
                else {
                    userData = new UserEntity_1.UserEntity();
                    userData.account = loginProto.account;
                    userData.nick_name = loginProto.nickname;
                    userData.sex = loginProto.sex;
                    userData.headimgurl = loginProto.headimgurl;
                    userData.ip = new_conn.ip;
                    userData.create_time = DateUtil_1.default.formatDateStr(DateUtil_1.default.now());
                    userData.last_login_time = userData.create_time;
                    userData = yield UserDao_1.UserDao.update_user(userData);
                    if (!userData) {
                        respModel.code = ErrorCode_1.ErrorCode.Code.Fail;
                        respModel.msg = "创建用户失败";
                    }
                }
                if (respModel.code == ErrorCode_1.ErrorCode.Code.Suc) {
                    let user = yield UserModel_1.UserModel.db2Model(userData);
                    new_conn.user = user;
                    let resourceObj = yield UserResourceDao_1.UserResourceDao.getResource(user.userid);
                    user.resource2Model(resourceObj);
                    let userRoomEntity = yield UserRoomDao_1.UserRoomDao.getUser(user.userid);
                    user.room_id = userRoomEntity.room_id;
                    respModel.data = user.model2proto();
                }
            }
            if (respModel.code == ErrorCode_1.ErrorCode.Code.Suc) {
                let respData = {
                    userInfo: respModel.data
                };
                new_conn.createMsgToClient(socketMsg.cmdIndex, socketMsg.cmdOrder, jhaoproto_1.JhaoProto.RespLogin, respData);
            }
            else {
                new_conn.sendErrorToClient(socketMsg.cmdOrder, respModel.code, respModel.msg);
            }
        });
    }
    static onReqPing(conn, socketMsg) {
        let protoPack = ProtoManager_1.ProtoManager.instance.decode(jhaoproto_1.JhaoProto.ReqPing, socketMsg.data);
        let needUpdate = WebVersionModel_1.WebVersionModel.getNeedUpate(ChannelConfig_1.ChannelConfig.Channel_Type.android, protoPack.version);
        let respData = {
            t: DateUtil_1.default.now(),
            n: needUpdate
        };
        conn.createMsgToClient(socketMsg.cmdIndex, socketMsg.cmdOrder, jhaoproto_1.JhaoProto.RespPing, respData);
    }
    static create_room(conn, socketMsg) {
        return __awaiter(this, void 0, void 0, function* () {
            let protoPack = ProtoManager_1.ProtoManager.instance.decode(jhaoproto_1.JhaoProto.req_create_room, socketMsg.data);
            let user = conn.user;
            let serverConfig = ServerConfig_1.ServerConfig.randomGameServer(protoPack.gameType);
            let serverStatus = yield SocketClientReqManager_1.SocketClientReqManager.instance.req_server_internal_get_server_status(serverConfig);
            Logger_1.Logger.log("create_room========1==", serverConfig);
            if (serverStatus == ServerConfig_1.ServerConfig.Status_Type.Weihu) {
                conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "服务器维护");
            }
            else {
                let inRoomId = RoomModel_1.RoomModel.isInRoom(user.userid);
                if (inRoomId > 0) {
                    conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "您已经在其他房间了哦:" + inRoomId);
                }
                else {
                    if (protoPack.gameType == GameConfig_1.GameConfig.Game_Type.Mj) {
                        let renShuIndex = RoomConfig_Mj_1.default.renshuConfig.indexOf(protoPack.roomConfigBase.renshu);
                        let jushuIndex = RoomConfig_Mj_1.default.jushuConfig.indexOf(protoPack.roomConfigBase.jushu);
                        protoPack.roomConfigBase.cost = RoomConfig_Mj_1.default.fangfeiConfig[renShuIndex][jushuIndex];
                    }
                    //平均
                    if (protoPack.roomConfigBase.costType == RoomConfig_1.RoomConfig.cost_type.pingjun) {
                        protoPack.roomConfigBase.cost = Math.floor(protoPack.roomConfigBase.cost / protoPack.roomConfigBase.renshu);
                    }
                    if (protoPack.roomConfigBase.distanceLimit > 0) { //开启了房间位置限制
                        // if (!user.location) {
                        //     respModel.code = ErrorCode.Code.Fail
                        //     respModel.msg = "创建房间失败，获取不到您位置"
                        // }
                        Logger_1.Logger.log("create_room========333==创建房间失败，获取不到您位置");
                        conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "创建房间失败，获取不到您位置");
                        return;
                    }
                    if (protoPack.roomType == RoomConfig_1.RoomConfig.Room_Type.Create) {
                        if (user.diamond < protoPack.roomConfigBase.cost) {
                            Logger_1.Logger.log("create_room========333==玩家钻石不足");
                            conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "玩家钻石不足");
                            return;
                        }
                    }
                    let room = {
                        roomId: RoomModel_1.RoomModel.generateRoomId(),
                        name: "",
                        roomType: protoPack.roomType,
                        gameType: protoPack.gameType,
                        creator: user.userid,
                        roomConfigBase: protoPack.roomConfigBase,
                        roomConfigMj: protoPack.roomConfigMj,
                        clubid: 0,
                        numOfTurns: 0,
                        createTime: DateUtil_1.default.now(),
                        serverId: serverConfig.id,
                        playerList: [],
                        gameInfoBase: {},
                        gameInfoMj: {}
                    };
                    let player = RoomPlayer_1.RoomPlayer.createPlayerByUser(user, room);
                    Logger_1.Logger.log("create_room========4444==", player);
                    if (RoomModel_1.RoomModel.insertPlayer(player, room)) {
                        let entity = yield RoomModel_1.RoomModel.insertRoom(room);
                        if (entity) {
                            inRoomId = RoomModel_1.RoomModel.isInRoom(user.userid);
                            if (inRoomId > 0) {
                                Logger_1.Logger.log("create_room========666==创建房间已经在其他房间");
                                conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "创建房间已经在其他房间" + inRoomId);
                                RoomManager_1.RoomManager.instance.delete_room([room.roomId], [room], ["创建房间已经在其他房间"]);
                                return;
                            }
                            ServerManager_1.ServerManager.instance.createRoom(room);
                            UserRoomDao_1.UserRoomDao.update_user(user.userid, room.roomId);
                            let protoResp = {
                                room: room,
                            };
                            conn.createMsgToClient(socketMsg.cmdIndex, socketMsg.cmdOrder, jhaoproto_1.JhaoProto.resp_create_room, protoResp);
                        }
                        else {
                            Logger_1.Logger.log("create_room========7777==创建房间时数据库失败");
                            conn.sendErrorToClient(socketMsg.cmdOrder, jhaoproto_1.JhaoProto.ErrorCodeWs.Fail, "创建房间时数据库失败");
                            return;
                        }
                    }
                    else {
                        Logger_1.Logger.log("create_room========55555==插入玩家失败");
                    }
                }
            }
        });
    }
    static notify_update_gems(userid) {
        // SocketConnectionManager.instance.socketConnMap.forEach(async (conn: SocketConnection, key: number) => {
        //     if (conn.isLogin() && conn.user) {
        //         if (conn.user.userid == userid) {
        //             let respModel: ResponseModel = new ResponseModel()
        //             conn.user.gems = await UserDao.getGems(userid);
        //             respModel.data = conn.user.gems
        //             return
        //         }
        //     }
        // });
    }
    static notify_update_coins(userid) {
        SocketConnectionManager_1.SocketConnectionManager.instance.socketConnMap.forEach((conn, key) => __awaiter(this, void 0, void 0, function* () {
            if (conn.isLogin() && conn.user) {
                if (conn.user.userid == userid) {
                    let respModel = new ResponseModel_1.ResponseModel();
                    // conn.user.coins = await UserDao.getCoins(userid)
                    // respModel.data = conn.user.coins
                    // conn.createMsgToClient(0, ProtoConfig.notify_update_coins, respModel)
                    RoomManager_1.RoomManager.instance.checkUpdatePlayerCoin(conn.user);
                    return;
                }
            }
        }));
    }
}
exports.HallServer_SocketMsgHandler = HallServer_SocketMsgHandler;
